package com.hzeport.bgs22emduty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzeport.bgs22emduty.config.exception.HdcException;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.dutyTel.DutyTelDTO;
import com.hzeport.bgs22emduty.dto.dutyTel.DutyTelVO;
import com.hzeport.bgs22emduty.dto.dutyTel.IdDTO;
import com.hzeport.bgs22emduty.dto.dutyTel.ParamDutyVO;
import com.hzeport.bgs22emduty.entity.BaseCustomPhone;
import com.hzeport.bgs22emduty.entity.ParamDuty;
import com.hzeport.bgs22emduty.enums.STypeEnum;
import com.hzeport.bgs22emduty.enums.SettingModeEnum;
import com.hzeport.bgs22emduty.outbound.BaseCustomPhoneRepositoy;
import com.hzeport.bgs22emduty.outbound.ParamDutyRepository;
import com.hzeport.bgs22emduty.service.DutyTelService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class DutyTelServiceImpl implements DutyTelService {

    private final LoginCompoentService loginCompoentService;
    private final BaseCustomPhoneRepositoy baseCustomPhoneRepositoy;
    private final ParamDutyRepository paramDutyRepository;

    @Override
    public List<DutyTelVO> list() {
        final String customsId = this.customsId();
        final List<BaseCustomPhone> list = baseCustomPhoneRepositoy.list(new LambdaQueryWrapper<BaseCustomPhone>()
                .eq(BaseCustomPhone::getCustomId, customsId)
                .eq(BaseCustomPhone::getSettingMode, SettingModeEnum.SETTINGS_PAGE.getCode()));
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        final List<String> paramDutyIds = list.stream().map(BaseCustomPhone::getParamDutyId)
                .distinct().collect(Collectors.toList());
        // 查询相关的值班时段数据
        final Map<String, ParamDuty> map = paramDutyRepository.queryRltParamDuty(paramDutyIds);

        return list.stream().map(item -> {
            final DutyTelVO vo = new DutyTelVO();
            vo.setId(item.getId());
            vo.setSTypeText(STypeEnum.getDescByCode(item.getSType()));
            vo.setPhoneTel(item.getPhoneTel());
            final ParamDuty paramDuty = map.get(item.getParamDutyId());
            if (null == paramDuty) {
                log.error("BASE_CUSTOM_PHONE中ID为{}的数据，PARAM_DUTY_ID字段未匹配到关联数据", item.getId());
                throw new HdcException("数据异常");
            }
            vo.setTimeString(paramDuty.generateTimeString());
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public void create(DutyTelDTO dutyTelDTO) {
        final String customsId = this.customsId();
        // 查询当前海关已配置值班电话
        final List<BaseCustomPhone> list = baseCustomPhoneRepositoy.list(new LambdaQueryWrapper<BaseCustomPhone>()
                .eq(BaseCustomPhone::getCustomId, customsId)
                .eq(BaseCustomPhone::getSettingMode, SettingModeEnum.SETTINGS_PAGE.getCode()));
        final MultiValuedMap<String, String> existingMap = list.stream().collect(
                ArrayListValuedHashMap::new,
                (collect, existingOne)
                        -> collect.put(existingOne.getSType(), existingOne.getParamDutyId()),
                MultiValuedMap::putAll
        );
        final List<String> paramDutyIds = dutyTelDTO.getParamDutyIdList();
        final List<BaseCustomPhone> baseCustomPhones = dutyTelDTO.getSTypeList().stream().distinct()
                .flatMap(sType -> paramDutyIds.stream().distinct()
                        .map(paramDutyId -> {
                            if (existingMap.containsMapping(sType, paramDutyId)) {
                                throw new HdcException("同值班类型，值班时段值班电话已配置");
                            }
                            final BaseCustomPhone entity = new BaseCustomPhone();
                            entity.setSettingMode(SettingModeEnum.SETTINGS_PAGE);
                            entity.setCustomId(customsId);
                            entity.setSType(sType);
                            entity.setParamDutyId(paramDutyId);
                            entity.setPhoneTel(dutyTelDTO.getPhoneTel());
                            return entity;
                        })
                ).collect(Collectors.toList());
        baseCustomPhoneRepositoy.saveBatch(baseCustomPhones);
    }

    @Override
    public void delete(IdDTO idDTO) {
        baseCustomPhoneRepositoy.removeById(idDTO.getId());
    }

    @Override
    public List<ParamDutyVO> paramDutyList() {
        final String customsId = this.customsId();
        final List<ParamDuty> list = paramDutyRepository.list(new LambdaQueryWrapper<ParamDuty>()
                .eq(ParamDuty::getDDept, customsId));
        return list.stream().map(item -> {
            final ParamDutyVO vo = new ParamDutyVO();
            vo.setId(item.getId());
            vo.setTimeString(item.generateTimeString());
            return vo;
        }).collect(Collectors.toList());
    }

    private String customsId() {
        final UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        // customsId（uuid） 不是 customsCode（7位）
        return userInfoDetailVO.getCustomscode();
    }
}
